interface UploadOptions {
  url: string // 上传地址
  filePath: string // 文件本地路径
  name?: string // 文件字段名，默认 'file'
  formData?: Record<string, any> // 附加字段
  header?: Record<string, string> // 自定义请求头（可选）
}

/**
 * 通用文件上传方法，适用于 uni.uploadFile
 * @returns Promise<上传响应>
 */
export function uploadFile<T = any>(options: UploadOptions): Promise<T> {
  const uploadUrl = import.meta.env.VITE_APP_BASE_API
  options.url = uploadUrl + options.url
  const {
    url,
    filePath,
    name = 'file',
    formData = {},
    header = {},
  } = options
  const token = getToken()

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url,
      filePath,
      name,
      formData,
      header: {
        Authorization: token,
      },
      success: (res) => {
        try {
          // 尝试解析 JSON 响应
          const data = JSON.parse(res.data)
          resolve(data as T)
        }
        catch (e) {
          // 非 JSON 响应
          resolve(res as unknown as T)
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}
